<template>
  <el-card  shadow="never" class="aui-card--fill">
    <div class="mod-sys__dict">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm"  label-position="right" label-width="100px">
        <el-form-item>
          <el-button type="primary" @click="dataFormSubmitHandle()">{{ this.dataForm.id?'保存公告':'发布公告'}}</el-button>
        </el-form-item>
        <el-form-item prop="noticeTopic" label="主题">
          <el-input v-model="dataForm.noticeTopic" placeholder="主题" show-word-limit maxlength="50"></el-input>
        </el-form-item>
        <el-form-item prop="target" label="发送对象">
          <el-select v-model="dataForm.target" placeholder="请选择">
            <el-option label="全体用户" :value=0></el-option>
            <el-option label="学生" :value=1></el-option>
            <el-option label="教师" :value=2></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="sort" label="排序">
          <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" label="排序"></el-input-number>
        </el-form-item> -->
        <el-form-item prop="noticeContent" label="公告内容">
          <!-- 公告内容 -->
          <mavon-editor 
            ref="md" 
            :toolbars="toolbars"
            v-model="dataForm.noticeContent"
            style="height:calc(120vh - 260px);border: 0;z-index: 0;" />
          <!-- maxlength="1000" show-word-limit -->
          <!-- <el-input type="textarea" v-model="dataForm.noticeContent" placeholder="请输入公告内容"></el-input> -->
        </el-form-item>
        <el-form-item v-if="this.dataForm.id"  label="已上传附件">
          <span v-for="item in noticefiles" :key="item.id" >
            <div class="delFile">
              {{ item.filename+`.`+item.suffix }}
              <el-button type="text" size="small" icon="el-icon-delete" @click="deletefile(item.id)">
                删除</el-button>
            </div>
              
          </span>
            
        </el-form-item>
        <el-form-item label="上传附件">
          <!-- <input type="file" ref="myfile"> -->
          <el-upload 
            class="upload-demo" 
            
            :show-file-list="true" 
            :auto-upload="false" 
            accept="txt,docx,pdf,doc,xls"
            multiple
            :limit="3"
            :file-list="fileList"
            :before-remove="beforeRemove"
            :on-success="uploadSuccess" 
            :on-exceed="handleExceed"
            :on-change="changeFile"
            action=""
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            >
            <!--  -->
            <!-- :data="dataForm" -->
            <!-- :headers='token' -->
            <!-- 
                  :ref="upload" 
                  :headers='token'
                  action="http://192.168.43.102:8081/student/comwenxian"
                  :with-credentials="true" 
                  
                  :drag="true" 
                  :on-error="error"
                  :before-remove="beforeRemove" -->
            <!-- <el-button size="middle" type="primary" icon="el-icon-upload2">上传文件</el-button> -->
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <!-- <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
            <div slot="tip" class="el-upload__tip">只能上传docx,txt,pdf,doc,xls文件,文件大小不超过100M</div>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="上传附件">
          <el-button type="primary" size="small" icon="el-icon-upload2" @click="addOrUpdateHandle(dataForm.id)">上传附件
          </el-button>
        </el-form-item> -->
      </el-form>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    </div>
  </el-card>
</template>

<script>
import servicesApi from '@/services/servicesApi'
import debounce from 'lodash/debounce'
import AddOrUpdate from './file-add-or-update.vue'
export default {
  data() {
    return {
      addOrUpdateVisible: false,
      fileList: [],
      noticefiles: [{}, {}, {}], //已经上传的文件
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: false, // 保存（触发events中的save事件）
        ishljs: false, //代码高亮
        // codeStyle:'agate',
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },
      dataForm: {
        id: '',
        noticeTopic: '',
        target: null,
        noticeContent: '',
      }
    }
  },
  computed: {
    dataRule() {
      return {
        noticeTopic: [
          { required: true, message: '必填项不能为空', trigger: 'blur' }
        ],
        target: [
          { required: true, message: '必填项不能为空', trigger: 'blur' }
        ],
        noticeContent: [
          { required: true, message: '必填项不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    AddOrUpdate
  },
  created() {
    this.dataForm.id = this.$route.params.id || 0
    // console.log('动态添加路由传入参数id=%s', this.dataForm.id)
    if (this.dataForm.id) {
      // console.log('修改公告')
      this.getInfo()
    } else {
      // console.log('新增公告')
    }
    
  },
  methods: {
    // 表单提交
    dataFormSubmitHandle: debounce(function() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        // this.$refs.upload.submit();
        let formData = new FormData();
        this.fileList.forEach(file => {
          formData.append('files', file.raw); //文件
        });
        formData.append('noticeTopic', this.dataForm.noticeTopic);
        formData.append('target', this.dataForm.target);
        formData.append('noticeContent', this.dataForm.noticeContent);
        // 添加其他非文件的参数，可以使用set() 方法
        // formData.set('config_type', this.json.config_typ);
        if (this.dataForm.id) { // 修改
          // console.log('修改公告')
          formData.append('noticeId', this.dataForm.id)
          servicesApi.updateNotice(formData).then(res => {
            if (res.data.code !== 200) {
              return this.$message.error(res.data.msg)
            }
            this.$message({
              message: '修改成功',
              type: 'success',
              duration: 500,
              onClose: () => {
                // this.visible = false
                // this.$emit('refreshDataList')
                // console.log('修改返回')
                this.closeCurrentTab();
              }
            })
          })
        } else {  // 新增
          // console.log('新增公告')
          servicesApi.addNoticeFile(formData).then(res => {
            if (res.data.code !== 200) {
              return this.$message.error(res.data.msg)
            }
            this.$message({
              message: '发布成功',
              type: 'success',
              duration: 500,
              onClose: () => {
                // console.log('新增返回')
                this.closeCurrentTab();
              }
            })
          })
        }
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    deletefile(fileId) {
      servicesApi.delNoticeFileById(fileId).then(res => {
        if (res.data.code !== 200) {
          return this.$message.error(res.data.msg)
        }
        this.$message({
          message: '删除成功',
          type: 'success',
          duration: 500,
          onClose: () => {
            this.getInfo()
          }
        })
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    changeFile(file, fileList) {
      // console.log('文件状态改变时的钩子')
      // console.log(file.name)
      // console.log(fileList)
      let Files = this.fileList
      // console.log('之前的文件%o', Files)
      if (this.fileList.length ==0) {
        this.fileList = fileList
        return this.$message.success('添加成功')
      }
      let isRepeat = false
      this.fileList.forEach(item => {
        // console.log(item)
        if (item.name == file.name) {
          isRepeat = true
        }
      });
      this.fileList.push(file)
      if (isRepeat) {
        this.$message.warning('文件已存在')
        this.fileList.pop()
      } else {
        this.$message.success('添加成功')
      }
      // console.log('上传文件%o', this.fileList)
      
      
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { })
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.fileList = fileList;
    },
    beforeUpload(file) {
      // console.log(file)
      const typeList = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain', 'application/msword', 'application/pdf', 'application/vnd.ms-excel']
      // const FileType = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      const size = 100
      let FileType = false
      const isLt = file.size / 1024 / 1024 < size;
      if (typeList.includes(file.type)) {
        // console.log('上传文件类型正确')
        FileType = true
      }
      if (!FileType) {
        this.$message.error('上传文件格式错误!');
      }
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过${size}MB!`);
      }
      return FileType && isLt;
    },
    uploadSuccess(res, file, fileList) {
      // console.log(file)
      // console.log(`======${file.name}文件上传成功=====`)
      if (res.code === 200) {
        this.$message.success('上传成功')
        // this.getDataList()//刷新页面
      } else {
        this.$message.error(res.msg)
      }
    },
    // 文件
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        // 当数据被修改后使用这个方法，会回调获取更新后的dom再渲染出来
        this.$refs['addOrUpdate'].init(id)
      })
    },
    submit() { //文件上传
      // // console.log("提交");
      let myfile = this.$refs.myfile;
      let files = myfile.files;
      // console.log(files)
      this.file = files[0];
      let formData = new FormData();
      formData.append('file', this.file);
      // 添加其他非文件的参数，可以使用set() 方法
      // formData.set('config_type', this.json.config_typ);
      this.loading = true;
      // 接口里面需要指定请求头 headers['Content-Type'] = 'multipart/form-data'
      servicesApi.submitWenxian(formData).then(res => {
        if (res.data.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 500,
          })
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 获取信息
    getInfo() {
      servicesApi.getNoticeInfoById(this.dataForm.id).then(res => {
        if (res.data.code !== 200) {
          return this.$message.error(res.data.msg)
        } else {
          // this.dataForm = {
          //   ...this.dataForm,
          //   ...res.data.data.notice
          // }
          this.noticefiles = res.data.data.noticefiles
          this.dataForm = res.data.data.notice
          // console.log(this.noticefiles)
        }
        
      })
    },
    // 关闭当前窗口
    closeCurrentTab(data) {
      let tabName = this.$store.state.contentTabsActiveName
      this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => item.name !== tabName)
      if (this.$store.state.contentTabs.length <= 0) {
        this.$store.state.sidebarMenuActiveName = this.$store.state.contentTabsActiveName = 'home'
        return false
      }
      if (tabName === this.$store.state.contentTabsActiveName) {
        this.$router.push({ name: this.$store.state.contentTabs[this.$store.state.contentTabs.length - 1].name})
      }
    },
    
  }
}
</script>
<style scoped>
.delFile{
  display: block;
  /* background-color: aqua; */
  font-size: 10px;
  margin: 10px;
}
</style>
